#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRandomGenerator>
#include <QMessageBox>
#include <QPushButton>
#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent, int initialPlayerCount)
    : QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_playerCount(qBound(2, initialPlayerCount, 3)),
    m_currentPlayer(0),
    m_positions(3, 0),
    m_gameOver(false)
{
    ui->setupUi(this);

    m_gameBoard = new GameBoard(this);
    ui->gameBoardContainer->layout()->addWidget(m_gameBoard);

    // 初始化玩家选择
    ui->playerComboBox->setCurrentIndex(m_playerCount - 2);

    // 连接信号槽
    connect(ui->rollButton, &QPushButton::clicked, this, &MainWindow::onRollButtonClicked);
    connect(ui->resetButton, &QPushButton::clicked, this, &MainWindow::onResetButtonClicked);
    connect(ui->playerComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &MainWindow::onPlayerCountChanged);

    updateStatus();
}

MainWindow::~MainWindow()
{
    delete m_gameBoard;
    delete ui;
}

void MainWindow::onRollButtonClicked()
{
    if(m_gameOver) return;

    // 生成骰子点数
    const int dice = QRandomGenerator::global()->bounded(1, 7);

    // 显示骰子结果弹窗
    QDialog diceDialog(this);
    diceDialog.setWindowTitle("骰子结果");
    diceDialog.setFixedSize(200, 150);

    QLabel diceLabel(QString::number(dice), &diceDialog);
    diceLabel.setAlignment(Qt::AlignCenter);
    diceLabel.setStyleSheet("font: bold 48px; color: #E91E63;");

    QPushButton btnOK("确定", &diceDialog);
    btnOK.setStyleSheet(
        "QPushButton {"
        "  background: #4CAF50;"
        "  color: white;"
        "  padding: 8px;"
        "  border-radius: 4px;"
        "}"
        "QPushButton:hover { background: #45a049; }"
        );

    QVBoxLayout layout(&diceDialog);
    layout.addWidget(&diceLabel);
    layout.addWidget(&btnOK);
    connect(&btnOK, &QPushButton::clicked, &diceDialog, &QDialog::accept);

    if(diceDialog.exec() == QDialog::Accepted) {
        processDiceResult(dice);
    }
}

void MainWindow::processDiceResult(int dice)
{
    int& currentPos = m_positions[m_currentPlayer];
    int newPos = currentPos + dice;

    // 处理终点逻辑
    currentPos = qMin(newPos, 80);
    m_gameBoard->movePlayer(m_currentPlayer, currentPos);
    updateStatus();

    if(currentPos >= 80) {
        showVictory();
        return;
    }

    // 处理特殊格子
    const GridType type = m_gameBoard->getGridType(currentPos);
    if(type != Normal) {
        handleSpecialGrid(type, currentPos);
    }

    // 切换玩家（排除额外回合）
    if(type != ExtraTurn) {
        m_currentPlayer = (m_currentPlayer + 1) % m_playerCount;
        updateStatus();
    }
}

void MainWindow::handleSpecialGrid(int type, int &position)
{
    QString message;
    bool needMove = true;

    switch(static_cast<GridType>(type)) {
    case BackToStart:
        message = "触发【回到起点】效果！";
        position = 0;
        break;
    case Forward3:
        message = "前进3格！";
        position = qMin(position + 3, 80);
        break;
    case Backward5:
        message = "后退5格！";
        position = qMax(position - 5, 0);
        break;
    case TeleportEnd:
        message = "直达终点！";
        position = 80;
        break;
    case ExtraTurn:
        message = "获得额外回合！";
        needMove = false;
        break;
    default:
        qWarning() << "未知格子类型：" << type;
        return;
    }

    // 显示事件提示弹窗
    QMessageBox::information(this, "特殊事件", message);

    if(needMove) {
        m_gameBoard->movePlayer(m_currentPlayer, position);
        updateStatus();
        if(position >= 80) showVictory();
    }
}

void MainWindow::onResetButtonClicked()
{
    m_positions.fill(0);
    m_currentPlayer = 0;
    m_gameOver = false;
    m_gameBoard->reset();
    updateStatus();
    ui->rollButton->setEnabled(true);
}

void MainWindow::onPlayerCountChanged(int index)
{
    const int newCount = index + 2;
    if(newCount == m_playerCount) return;

    m_playerCount = newCount;
    m_gameBoard->setVisiblePlayers(m_playerCount);
    onResetButtonClicked();
}

void MainWindow::showVictory()
{
    m_gameOver = true;

    QMessageBox msgBox(this);
    msgBox.setWindowTitle("游戏胜利");
    msgBox.setText(QString("玩家 %1 获胜！").arg(m_currentPlayer + 1));
    msgBox.setIconPixmap(QPixmap(":/icons/trophy.png").scaled(64, 64));

    QPushButton *btnNew = msgBox.addButton("新游戏", QMessageBox::AcceptRole);
    QPushButton *btnExit = msgBox.addButton("退出", QMessageBox::RejectRole);

    btnNew->setStyleSheet(
        "QPushButton {"
        "  background: #2196F3;"
        "  color: white;"
        "  padding: 8px 16px;"
        "  border-radius: 4px;"
        "}"
        );

    btnExit->setStyleSheet(
        "QPushButton {"
        "  background: #F44336;"
        "  color: white;"
        "  padding: 8px 16px;"
        "  border-radius: 4px;"
        "}"
        );

    if(msgBox.exec() == QMessageBox::AcceptRole) {
        onResetButtonClicked();
    } else {
        close();
    }
}

void MainWindow::updateStatus()
{
    QStringList status;
    for(int i = 0; i < m_playerCount; ++i) {
        status << QString("玩家%1: %2").arg(i+1).arg(m_positions[i]);
    }

    ui->statusLabel->setText(QString("当前玩家：玩家%1").arg(m_currentPlayer + 1));
    ui->positionsLabel->setText(status.join(" ｜ "));

    // 高亮当前玩家
    for(int i = 0; i < 3; ++i) {
        m_gameBoard->setPlayerColor(i, (i == m_currentPlayer) ? Qt::yellow : Qt::black);
    }
}
